/**
 * @author of2470
 *@date 2017/4/26
 *@description
 */
import * as React from "react";
import { Relax } from "iflux2";
import { transNormalTime, getEnvXSite, openNewWin } from "x-site-util";
import { Table, Icon, Button, Popconfirm, message } from "antd";
import NewPageModal from "./new-page-modal";
import ShareDialog from "./share-dialog";
import { domainListQL } from "../ql";
import { List, Map } from "immutable";
import { getSystemCode, getSystemCodeZip } from "../../common/const-value";
import GaUtil from "common-util/ga-util";
import ExpireLock from "expire-lock";
import NewGuide from "./new-guide";

const SystemCodeZip = getSystemCodeZip();
const weixinCustom = "${host}#/${pageType}/${pageCode}";
const systemCode = getSystemCode();

@Relax
export default class PageManageWx extends React.Component<any, any> {
  modal: any = {};

  constructor(props) {
    super(props);
    //url里guide=true说明是新用户  展示指引
    let hash = location.hash;
    let guide = "";
    if (hash && hash.split("?").length > 1) {
      let search = hash.split("?")[1];
      let params = search.split("&");
      for (let i = 0; i < params.length; i++) {
        let param = params[i].split("=");
        if (param.length > 1 && param[0] === "guide") {
          guide = param[1];
        }
      }
    }
    this.state = {
      visible: false,
      editing: "",
      guide
    };
  }

  static defaultProps = {
    totalCount: 0,
    pageSize: 0,
    pageNo: 1,
    pageTypeInfo: Map(),
    pageList: List(),
    domainInfo: domainListQL,
    platform: "",
    getPageList: () => {},
    deletePage: () => {},
    activateIndexPage: () => {},
    setPageTitle: () => {},
    getTemplateList: () => {},
    getPageTypeBtnList: () => {},
    copyPageInfo: () => {}
  };

  render() {
    const pageList = this.props.pageList;
    const columns = this.columns;
    let result;
    if (!this.props.loading && pageList.count() > 0) {
      let pagination = {
        total: this.props.totalCount,
        pageSize: this.props.pageSize,
        current: this.props.pageNo,
        onChange: this._changePage
      };
      result = (
        <Table
          bordered
          dataSource={pageList.toJS()}
          columns={columns}
          pagination={pagination}
          style={{ marginTop: "10px", textAlign: "center" }}
        />
      );
    } else if (!this.props.loading) {
      result = (
        <div className="no-page">
          <span>
            <Icon type="info-circle" />
          </span>
          <span>暂无页面，新建页面开始对您的站点进行装修吧！</span>
        </div>
      );
    }

    return (
      <div id="page-manage-content">
        {this.state.guide == "true" &&
          <NewGuide
            addNewPage={this._guideAddNewPage}
            closeGuide={this._closeGuide}
          />}
        <Button
          onClick={this._addNewPage.bind(this)}
          type="primary"
          size="large"
        >
          新增页面
        </Button>
        {result}
        <NewPageModal
          visible={this.state.visible}
          platform={this.props.platform}
          changeModalStatus={this._changeModalStatus}
        />
      </div>
    );
  }

  columns = [
    {
      title: "页面名称",
      dataIndex: "title",
      key: "title",
      width: "20%",
      render: (text, record, index) => {
        return (
          <div>
            {this.state.editing === index
              ? <input
                  defaultValue={text}
                  autoFocus={true}
                  onKeyPress={this._onKeyPressTitle.bind(this, record, index)}
                  onBlur={this._changeTitle.bind(this, record, index)}
                />
              : <div className="title-input">
                  <span>
                    {text || "页面标题"}
                  </span>
                  <a
                    href="javascript:;"
                    onClick={this._editTitle.bind(this, index)}
                  >
                    <Icon type="edit" />
                  </a>
                </div>}
          </div>
        );
      }
    },
    {
      title: "页面类型",
      dataIndex: "pageType",
      key: "pageType",
      render: text => {
        let pageTypeText = "";
        if (this.props.pageTypeInfo.get(text)) {
          pageTypeText = this.props.pageTypeInfo.get(text).get("name");
        }
        return (
          <span>
            {pageTypeText}
          </span>
        );
      }
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: text =>
        <span>
          {text === "published" ? "已发布" : "未发布"}
        </span>
    },
    {
      title: "修改时间",
      dataIndex: "updateTime",
      key: "updateTime",
      render: text =>
        <span>
          {text && transNormalTime(text)}
        </span>
    },
    {
      title: "操作",
      dataIndex: "tplId",
      key: "action",
      width: "30%",
      render: (text, record, index) => {
        let qrCodeUrl = this._getQrUrl(record);
        let showCopy = this._showCopyLink(record, qrCodeUrl);
        let copyOrShare;
        if (
          showCopy &&
          (showCopy == "homePage" ||
            showCopy == "poster" ||
            showCopy == "service")
        ) {
          copyOrShare = (
            <span>
              <span className="ant-divider" />
              <ShareDialog
                pageInfo={record}
                platform={this.props.platform}
                qrcodeurl={qrCodeUrl}
              />
            </span>
          );
        }
        let indexTitle = systemCode === "d2c" ? "商城首页" : "订货首页";
        return (
          <span>
            {record.pageType !== "roulette"
              ? <a
                  href="javascript:;"
                  onClick={this._getEditUrl.bind(this, record)}
                >
                  编辑
                </a>
              : null}
            {record.pageType === "index" && record.activated
              ? <span>
                  <span className="ant-divider" />
                  <span>
                    {indexTitle}
                  </span>
                </span>
              : null}
            {this._showCopyPageBtn(record)
              ? <span>
                  <span className="ant-divider" />
                  <Popconfirm
                    title="确定复制该页面吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={this._confirmCopyPage.bind(this, record)}
                  >
                    <a href="#">复制</a>
                  </Popconfirm>
                </span>
              : null}
            {this._showDelBtn(record)
              ? <span>
                  <span className="ant-divider" />
                  <Popconfirm
                    title="确定删除该页面吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={this._confirmDelete.bind(this, record)}
                  >
                    <a href="#">删除</a>
                  </Popconfirm>
                </span>
              : null}
            {record.pageType === "index" &&
            !record.activated &&
            record.status === "published"
              ? <span>
                  <span className="ant-divider" />
                  <Popconfirm
                    title="确定要设为首页吗？"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={this._confirmActivateIndex.bind(this, record)}
                  >
                    <a href="#" className="ant-dropdown-link">
                      设为首页
                    </a>
                  </Popconfirm>
                </span>
              : null}
            {copyOrShare}
          </span>
        );
      }
    }
  ];

  @ExpireLock()
  _getEditUrl(record) {
    let editURL = getEnvXSite() + record.editURL + "?sc=" + SystemCodeZip;
    openNewWin(editURL);
  }

  _guideAddNewPage = () => {
    this.setState({ guide: false }, () => {
      this._addNewPage();
    });
  };

  //关闭指引
  _closeGuide = () => {
    this.setState({ guide: false });
  };

  //编辑title
  @ExpireLock()
  _editTitle(index) {
    GaUtil.addPageEvent({
      eventAction: "编辑页面名称",
      eventLabel: "",
      platform: this.props.platform
    });
    this.setState({ editing: index });
  }

  //在input输入框里点击enter
  _onKeyPressTitle = (record, index, e) => {
    if (e.charCode === 13) {
      this._changeTitle(record, index, e);
    }
  };

  //改变title
  _changeTitle = (record, index, e) => {
    let value = e.target.value;
    this.setState({ editing: "" });
    let length = this._getStrLength(value);
    if (length > 0 && length <= 20) {
      if (record.title !== value) {
        this.props
          .setPageTitle({
            pageType: record.pageType,
            pageCode: record.pageCode,
            platform: this.props.platform,
            title: value,
            index
          })
          .then(
            () => {
              message.success("修改页面名称成功！", 3);
            },
            err => {
              console.log(err);
              message.error("修改错误，请重试！", 3);
            }
          );
      }
    } else {
      message.error("页面名称不能为空并且长度不能超过20个字符！", 4);
    }
  };

  _getStrLength = str => {
    let reg = /[\u4e00-\u9fa5]/g;
    let chinese = str.match(reg) || [];
    let alphanumeric = str.replace(reg, "") || "";
    return chinese.length * 2 + alphanumeric.length;
  };

  //添加新页面  打开模态框
  @ExpireLock()
  async _addNewPage() {
    this.props.getPageTypeBtnList({
      platform: this.props.platform
    });
    await this.props.getTemplateList({
      includePageTypeList: ["index"],
      platform: this.props.platform
    });
    this._changeModalStatus(true);
    GaUtil.addPageEvent({
      eventAction: "点击新增页面",
      eventLabel: "",
      platform: this.props.platform
    });
  }

  //展示或者隐藏模态框
  _changeModalStatus = visible => {
    if (!visible) {
      this.props.getPageList({
        platform: this.props.platform,
        pageNo: 0,
        pageSize: this.props.pageSize
      });
    }
    this.setState({ visible });
  };

  //分页搜索
  _changePage = pageNo => {
    this.props.getPageList({
      platform: this.props.platform,
      pageNo: pageNo - 1,
      pageSize: this.props.pageSize
    });
  };

  //确认删除页面
  @ExpireLock()
  _confirmDelete(record) {
    GaUtil.addPageEvent({
      eventAction: "删除页面",
      eventLabel: record.tplCode,
      platform: this.props.platform
    });
    let num = (this.props.totalCount - 1) % this.props.pageSize;
    let pageNo = num > 0 ? this.props.pageNo - 1 : this.props.pageNo - 2;
    pageNo = pageNo < 0 ? 0 : pageNo;
    this.props
      .deletePage({
        platform: this.props.platform,
        pageType: record.pageType,
        pageCode: record.pageCode,
        pageSize: this.props.pageSize,
        pageNo
      })
      .then(() => {
        message.success("删除页面成功！");
      })
      .catch(err => {
        console.log(err);
        message.warn("删除页面失败！");
      });
  }

  //确认设为首页
  @ExpireLock()
  _confirmActivateIndex(record) {
    GaUtil.addPageEvent({
      eventAction: "设为首页",
      eventLabel: record.tplCode,
      platform: this.props.platform
    });
    this.props
      .activateIndexPage({
        platform: this.props.platform,
        pageCode: record.pageCode,
        pageSize: this.props.pageSize
      })
      .then(() => {
        message.success("设为首页成功！");
      })
      .catch(err => {
        console.log(err);
        message.warn("设为首页失败！");
      });
  }

  //是否展示删除按钮
  _showDelBtn = pageInfo => {
    if (
      ("index" === pageInfo.pageType && pageInfo.activated) ||
      ["roulette"].indexOf(pageInfo.pageType) >= 0 ||
      ["classify", "goodsInfo", "goodsList", "service"].indexOf(
        pageInfo.pageCode
      ) >= 0 ||
      pageInfo.fakeData ||
      ("index" === pageInfo.pageType && this.props.indexCount === 1)
    ) {
      return false;
    } else {
      return true;
    }
  };

  //是否显示复制页面按钮
  _showCopyPageBtn = pageInfo => {
    if (
      ["classify", "goodsInfo", "goodsList", "service"].indexOf(
        pageInfo.pageCode
      ) >= 0 ||
      pageInfo.fakeData
    ) {
      return false;
    } else {
      return true;
    }
  };

  //复制页面信息
  @ExpireLock()
  _confirmCopyPage(pageInfo) {
    GaUtil.addPageEvent({
      eventAction: "复制页面",
      eventLabel: pageInfo.tplCode,
      platform: this.props.platform
    });
    let length = this._getStrLength(pageInfo.title);
    if (pageInfo.title.indexOf("[复制]") > 0 && length > 20) {
      message.warn("页面名称长度不符合要求，不能复制！");
      return;
    } else if (pageInfo.title.indexOf("[复制]") < 0 && length + 6 > 20) {
      message.warn("页面名称长度不符合要求，不能复制！");
      return;
    }
    let id = pageInfo.id || pageInfo["_id"];
    this.props
      .copyPageInfo(id)
      .then(() => {
        message.success("复制页面成功！");
        this.props.getPageList({
          platform: this.props.platform,
          pageSize: this.props.pageSize,
          pageNo: 0
        });
      })
      .catch(err => {
        console.log(err);
        message.warn("复制页面失败！");
      });
  }

  //是否显示复制链接
  _showCopyLink = (data, url) => {
    let flag = "";
    const basePageTypeList = ["classify", "goodsInfo", "goodsList"]; //基础页的页面类型
    const posterPageTypeList = ["custom", "poster", "liveShow", "article"]; //海报页的页面类型
    if (
      data.status == "published" &&
      basePageTypeList.indexOf(data.pageType) >= 0
    ) {
      flag = "basePage"; //基础页
    } else if (data.activated) {
      flag = "homePage"; //首页
    } else if (
      data.status == "published" &&
      posterPageTypeList.indexOf(data.pageType) >= 0
    ) {
      flag = "poster"; //海报页
    } else if (data.pageType == "service") {
      flag = "service";
    }
    return url && flag;
  };

  //获取前端商城url
  _getQrUrl = _pageInfo => {
    let weixinBasicUrl = this.props.domainInfo.weixin;
    let pcBasicUrl = this.props.domainInfo.pc;
    let qrcodeurl = "#";
    if (this.props.platform == "pc") {
      //pc端  所有的都直接跳到store首页
      return ["poster", "custom", "classify"].indexOf(_pageInfo.pageType) >= 0
        ? pcBasicUrl + `/${_pageInfo.pageType}/${_pageInfo.pageCode}`
        : pcBasicUrl;
    } else if (this.props.platform == "weixin") {
      //微信端的首页地址
      if (_pageInfo.pageType == "index") {
        return weixinBasicUrl;
      } else {
        //微信的其他页面
        qrcodeurl = weixinCustom
          .replace("${host}", weixinBasicUrl)
          .replace("${pageType}", _pageInfo.pageType)
          .replace("${pageCode}", _pageInfo.pageCode);
        return qrcodeurl;
      }
    } else if (this.props.platform == "app") {
      //返回app的下载 地址
      return this.props.domainInfo.app;
    }
  };
}
